<script setup>
  import { ref, computed, reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import taskApi from '@/apis/task.js'
  // 组件 ref
  const popup = ref(null)
  // 异常日期
  const timePicker = ref('') // √
  const transportTaskId = ref('') //任务id √
  const exceptionPlace = ref('') //上报的位置√
  const exceptionType = ref('') //异常类型 √完成一半
  const exceptionDescribe = ref('') //异常描述
  const exceptionImagesList = ref([]) //异常现场照片
  // 定义 popup 组件展示的数据
  const exceptionTypes = reactive([
    { text: '发动机启动困难', checked: false },
    { text: '不着车，漏油', checked: false },
    { text: '照明失灵', checked: false },
    { text: '排烟异常、温度异常', checked: false },
    { text: '其他问题', checked: false },
  ])

  // 文件提示
  const exceptTime = computed(() => {
    return timePicker.value || '请选择'
  })

  onLoad(({ taskid }) => {
    transportTaskId.value = taskid
  })

  // 打开地图
  async function onLocationChoose() {
    // uniapp提供的打开地图的方法（h5和微信小程序选择的是腾讯地图，app用的是高德）
    // 由于app里面用的是高德地图，所以需要再chooseLocation中传入经纬度才能正常获取周边地址列表
    // 解决：使用uni.getLocation() 来获取经纬度
    let { latitude, longitude } = await uni.getLocation({})
    let { address } = await uni.chooseLocation({ latitude, longitude })
    console.log('地图返回结果：', latitude, longitude, address)
    exceptionPlace.value = address
  }

  // 点击类型弹层确认按钮
  function onPopupConfirm() {
    popup.value.close()
  }

  // 打开弹层
  function onPopupOpen() {
    popup.value.open()
  }

  // 异常类型change事件
  function onCheckboxChange(index) {
    console.log(index)
    // 1. 根据索引修改exceptionTypes数组中的对象属性checked
    exceptionTypes[index].checked = !exceptionTypes[index].checked

    // console.log(ev)
    // let value = ev.detail.value[0]
    // exceptionType.value += value + '|'
    // console.log(exceptionType.value)
  }

  // 计算描述信息长度
  const descLength = computed(() => {
    return exceptionDescribe.value.length
  })
  // 计算属性：过滤出exceptionTypes中checked为ture的内容
  const trueTypes = computed(() => {
    // 返回异常类型拼接字符串
    let trueTypesList = exceptionTypes.filter((item) => item.checked)
    let typesString = trueTypesList.map((item) => item.text).join('|')
    return typesString
  })

  // 提交表单数据到服务器
  async function onSubmit() {
    try {
      const formData = {
        transportTaskId: transportTaskId.value,
        exceptionTime: timePicker.value,
        exceptionPlace: exceptionPlace.value,
        exceptionType: trueTypes.value,
        exceptionDescribe: exceptionDescribe.value,
        exceptionImagesList: exceptionImagesList.value,
      }
      let { code, msg } = await taskApi.except(formData)
      if (code !== 200) {
        return uni.utils.toast(msg)
      }

      // 清空页面栈中的所有页面后（销毁），重新打开一个新页面
      uni.reLaunch({
        url: '/pages/task/index',
      })
    } catch (err) {}
  }
</script>

<template>
  <view class="page-container">
    <scroll-view class="scroll-view" scroll-y>
      <view style="margin: 30rpx" class="scroll-view-wrapper">
        <uni-list :border="false">
          <uni-list-item show-arrow title="异常时间">
            <template v-slot:footer>
              <uni-datetime-picker v-model="timePicker">
                <view class="picker-value">{{ exceptTime }}</view>
              </uni-datetime-picker>
            </template>
          </uni-list-item>

          <uni-list-item
            show-arrow
            clickable
            ellipsis="1"
            @click="onLocationChoose"
            title="上报位置"
            :rightText="exceptionPlace || '请选择'"
          />
          <uni-list-item
            show-arrow
            clickable
            @click="onPopupOpen"
            title="异常类型"
            :rightText="trueTypes || '请选择'"
          />
          <uni-list-item direction="column" title="异常描述">
            <template v-slot:footer>
              <view class="textarea-wrapper">
                <textarea
                  v-model="exceptionDescribe"
                  class="textarea"
                  placeholder="请输入异常描述"
                ></textarea>
                <view :class="{ error: descLength > 50 }" class="words-count"
                  >{{ descLength }}/50</view
                >
              </view>
            </template>
          </uni-list-item>
          <uni-list-item
            :border="false"
            style="margin-top: -30rpx"
            direction="column"
            title="上传图片（最多6张）"
          >
            <template v-slot:footer>
              <uni-file-picker
                v-model="exceptionImagesList"
                limit="6"
              ></uni-file-picker>
            </template>
          </uni-list-item>
        </uni-list>
      </view>
    </scroll-view>
    <view class="fixbar">
      <button class="button disable" @click="onSubmit">提交</button>
    </view>
    <!-- 异常类型弹层 -->
    <uni-popup ref="popup" :mask-click="false" type="bottom">
      <uni-list class="popup-action-sheet">
        <uni-list-item>
          <template v-slot:header>
            <view class="header">选择类型</view>
          </template>
        </uni-list-item>

        <uni-list-item
          v-for="(item, index) in exceptionTypes"
          :key="item.text"
          :title="item.text"
        >
          <template v-slot:footer>
            <checkbox-group @change="onCheckboxChange(index)" class="checkbox">
              <checkbox
                :value="item.text"
                :checked="item.checked"
                color="#EF4F3F"
              />
            </checkbox-group>
          </template>
        </uni-list-item>

        <uni-list-item>
          <template v-slot:body>
            <button @click="onPopupConfirm" class="button">确定</button>
          </template>
        </uni-list-item>
      </uni-list>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  @import './index.scss';
</style>
